package fuzion24.device.vulnerability.test;

import android.app.Application;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;

import com.evernote.android.job.JobManager;

import java.io.File;

import fuzion24.device.vulnerability.test.job.AndroidVTSJobCreator;

/**
 * Handles the application lifecycle.
 */

public class AndroidVTSApplication extends Application {

    public String downloadFilename;

    // Download manager.
    public DownloadManager downloadManager;
    public BroadcastReceiver onComplete = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String apkDirectory = String.format("%s/%s", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), downloadFilename);
            Intent downloadIntent = new Intent(Intent.ACTION_VIEW);

            downloadIntent.setDataAndType(Uri.fromFile(new File(apkDirectory)), "application/vnd.android.package-archive");
            downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            startActivity(downloadIntent);
        }

    };

    @Override
    public void onCreate() {
        super.onCreate();

        // Set the download callbacks.
        downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

        registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        // Start the job to check for updates.
        JobManager.create(this).addJobCreator(new AndroidVTSJobCreator());
    }

    @Override
    public void onTerminate() {
        super.onTerminate();

        unregisterReceiver(onComplete);
    }
}
